package main

import(
    "crypto/md5"
    "fmt"
)

type AppInfo struct {
	AppID             string   `json:"app_id"`
	PasswdShadow      string   `json:"passwd_shadow"`
	AllowedContainers []string `json:"container_allowed"`
    TrustedClientKeys map[string]string `json:"trusted_client_keys"`
}

func (a *AppInfo) Auth(passwd, salt string) bool {
    md5sum := md5.Sum([]byte(passwd+salt))
    return  fmt.Sprintf("%x",md5sum)==a.PasswdShadow
}
func (a *AppInfo) AuthContainer(cid string) bool {
    for _,id:= range a.AllowedContainers{
        if cid==id{
            return true
        }
    }
    return false
}


func ParseCommandAndCid(appid string, input []string) (output []string, cid string) {//解析ssh命令行  并转换成宿主机的命令行
	if len(input) < 1 {
		return
	}
    if input[0] == "reg" {
        output = []string{"reg"}
        return
    }
	if input[0] == "bash" {
		output = []string{"sudo", "-u", appid, "bash"}
		return
	}
	if input[0] == "ps" {
		output = append([]string{"docker"}, input...)
		return
	}
	if len(input) == 2 {
		if cmd := input[0]; cmd == "start" || cmd == "stop" || cmd == "restart" || cmd == "stats" {
			output = append([]string{"docker"}, input...)
			cid = input[1]
		} else if cmd == "exec" {
			cid = input[1]
			output = append([]string{"docker"}, cmd, "-it", input[1], "bash")
		}
		return
	}
	if input[0] == "logs" {
		if len(input) == 2 {
			cid = input[1]
			output = append([]string{"docker"}, input...)
			return
		} else if len(input) == 3 && input[2] == "-f" {
			cid = input[2]
			output = append([]string{"docker"}, input...)
			return
		}
	}
	if input[0] == "rm" {
		if len(input) == 2 {
			cid = input[1]
			output = append([]string{"docker"}, input...)
			return
		} else if len(input) == 3 && input[2] == "-f" {
			cid = input[2]
			output = append([]string{"docker"}, input...)
			return
		}
	}
	return
}
